/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable react-hooks/rules-of-hooks */
import React, { useState, useEffect, useRef } from 'react';
import { Space, Card, Divider, Typography, Input, Button, Avatar, message } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import { UserOutlined, AliwangwangOutlined } from '@ant-design/icons';
import { request } from 'umi';
import { GiftedChat, IMessage, User } from 'react-native-gifted-chat'
const { Meta } = Card;
const { Text, Link, Title } = Typography;
const { TextArea } = Input;

const index: React.FC = () => {
  const [data, setdata] = useState('');
  const [myid, setmyid] = useState(0);
  const [otherids, setotherids] = useState([111]);
  const [curotherid, setcurotherid] = useState(0);
  const [input, setinput] = useState('');
  const [interval, setinterval] = useState(null);
  const [inputdisabled, setinputdisabled] = useState(true);
  const textareaEL = useRef(null);

  const scrollToBottom = () => {
    if (textareaEL) {
      textareaEL.current.scrollTop = textareaEL.current.scrollHeight;
    }
  };

  const getusername = async () => {
    const res = await request('/api/currentUser');
    return res.data.access;
  };

  useEffect(() => {
    request('/api/currentUser').then((res) => {
      if (res.data.access === 'czh') {
        setmyid(222);
      }
    });
    // const timer = setInterval(() => {
    //   console.log(curotherid)
    //   if (curotherid !== 0) {
    //     handleGetData(myid,curotherid)
    //     console.log('test')
    //   }
    // }, 5000);
    return () => {
      if (interval !== null) {
        clearInterval(interval);
        setInterval(null);
      }
    };
  }, []);

  const timerGetData = (curotherid) => {
    return setInterval(() => {
      console.log(curotherid);
      if (curotherid !== 0) {
        handleGetData(myid, curotherid);
      }
    }, 1000);
  };

  const handleGetData = async (myid, curotherid) => {
    const val = {
      chatId: 59,
      send: {
        accountId: curotherid,
        accountIdentity: 1,
      },
      receive: {
        accountId: myid,
        accountIdentity: 2,
      },
      count: 10,
      startTime: 1549348024,
      endTime: 1749390553,
      lastMsgKey: '',
    };
    await request('http://localhost:8080/api/consulting/chat/receive', {
      method: 'post',
      data: val,
    })
      .then((res) => {
        const msglist = res.payload.MsgList;
        let msgs = '';
        msglist.map((msg) => {
          const name = msg.From_Account;
          const content = msg.MsgBody[0].MsgContent.Text;
          let date = new Date(msg.MsgTimeStamp);
          msgs = msgs + ('--' + name + '--' + ':\n' + content + '\n\n');
        });
        console.log(new Date().getTime());
        setdata(msgs);
      })
      .catch((err) => console.log(err));
  };

  const handleAddSendInput = async (content: string, myid: number, curotherid: number) => {
    const val = {
      chatId: 59,
      syncOtherMachine: 1,
      send: {
        accountId: myid,
        accountIdentity: 2,
      },
      receive: {
        accountId: curotherid,
        accountIdentity: 1,
      },
      msgType: 1,
      msgContent: content,
    };
    await request('http://localhost:8080/api/consulting/chat/send', {
      method: 'post',
      data: val,
    }).catch((err) => console.log(err));
  };

  const handleAddInput = async () => {
    const res = await request('/api/currentUser');
    let t = data + ('--' + res.data.access + '--:\n' + input + '\n\n');
    handleAddSendInput(input, myid, curotherid);
    // setdata(t);
    scrollToBottom();
  };

  const otheridslist = () => {
    return otherids.map((otherid) => {
      return (
        <>
          {/* <Card  style={{height: 50, width: 200}} bordered={false}>
          <Avatar style={{ backgroundColor: '#87d068' }} icon={<UserOutlined />} /> {otherid}
          </Card> */}
          <Meta
            avatar={<Avatar src="https://joeschmoe.io/api/v1/random" />}
            title={otherid}
            description={
              <Button
                type="primary"
                icon={<AliwangwangOutlined />}
                size="small"
                onClick={() => {
                  message.info('开启与 ' + otherid + ' 的会话');
                  console.log('test' + otherid);
                  setcurotherid(otherid);
                  handleGetData(myid, otherid);
                  setinterval(timerGetData(otherid));
                  setinputdisabled(false);
                }}
              >
                开启会话
              </Button>
            }
          />
          <Divider />
        </>
      );
    });
  };

  return (
    <Space>
      <Card bordered={true} style={{ height: 700, width: 300 }}>
        <Title level={4}>用户列表</Title>
        <Divider />
        {otheridslist()}
      </Card>
      <div style={{ height: 700, width: 800 }}>
        <Card style={{ height: 600, width: 800 }}>
          <Title level={4}>聊天窗口</Title>
          <Divider />
          <TextArea
            ref={textareaEL}
            style={{ color: 'HighlightText' }}
            disabled={true}
            value={data}
            rows={20}
          />
        </Card>
        <Card style={{ height: 100, width: 800 }}>
          <Space>
            <TextArea
              value={input}
              onChange={(e) => setinput(e.target.value)}
              style={{ height: 60, width: 700 }}
              disabled={inputdisabled}
            />
            <Button
              onClick={() => {
                handleAddInput();
                setinput('');
              }}
              type="primary"
              style={{ height: 60 }}
            >
              提交
            </Button>
          </Space>
        </Card>
      </div>
    </Space>
  );
};

export default index;
